package com.ybkj.daijia.server.event.listener.zhuan;

import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.event.model.MemberNoticeEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderCreatePaidanEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderPaidanEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.MemberNotice;
import com.ybkj.daijia.server.model.NoticeXPassenger;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberNoticeService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.NoticeXPassengerService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuan.Order;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ZhuanOrderCreatePaidanEventListener implements
    ApplicationListener<ZhuanOrderCreatePaidanEvent> {

    private static final Logger logger = LoggerFactory
        .getLogger(ZhuanOrderCreatePaidanEventListener.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private ZhuancheService zhuancheService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ErrandService errandService;

    @Autowired
    private FreightService freightService;

    @Autowired
    private ZhuanxianService zhuanxianService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberNoticeService memberNoticeService;

    @Autowired
    private NoticeXPassengerService noticeXPassengerService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    @Override
    @Async
    public void onApplicationEvent(ZhuanOrderCreatePaidanEvent event) {
        Long orderId = (Long) event.getSource();
        Long employId = event.getEmployId();
        Order order = zhuancheService.findOne(orderId);
        Driver driver = driverService.findOne(employId);

        boolean manglu = true;

        if (driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            if (driver.getDriverJobType().contains(Driver.DriverJobType.zhuanche.toString())) {
                if (order.getStatus() == Order.ORDER_STATUS_NEW) {
                    Car car = zhuancheService.findCar(driver.getCarId());
                    if (null != car) {
                        if (car.getCarTypeId().equals(order.getCarTypeId())) {
                            Map<String, Object> map2 = getDriverBusy(driver.getId());
                            Boolean success = (Boolean) map2.get("success");
                            if (success) {

                                manglu = false;

                                Result<Order> result = zhuancheService.paidan(driver, order, "系统");

                                if (result.isSuccess()) {
                                    // 派单事件
                                    ZhuanOrderPaidanEvent paidanEvent = new ZhuanOrderPaidanEvent(
                                        order.getId());
                                    applicationEventMulticaster.multicastEvent(paidanEvent);
                                }
                            }
                        }
                    }
                }
            }
        }

        if (manglu) {
            try {
                Passenger passenger = memberService.findOnePassenger(order.getPassengerId());

                MemberNotice memberNotice = new MemberNotice();
                memberNotice.setCompanyId(passenger.getCompanyId());
                memberNotice.setContent("您选择的服务人员" + driver.getName() + "已忙碌，正在为您改派其他服务人员");
                memberNotice.setOperating("系统");
                memberNotice.setPassengerIds("," + passenger.getId() + ",");
                memberNoticeService.insertRecord(memberNotice);

                NoticeXPassenger noticeXPassenger = new NoticeXPassenger();
                noticeXPassenger.setPassengerId(passenger.getId());
                noticeXPassenger.setNoticeId(memberNotice.getId());
                noticeXPassenger.setHasRead(false);
                noticeXPassengerService.save(noticeXPassenger);

                List<Passenger> passengerList = new ArrayList<Passenger>();
                passengerList.add(passenger);

                MemberNoticeEvent memberNoticeEvent = new MemberNoticeEvent(memberNotice,
                    passengerList);
                applicationEventMulticaster.multicastEvent(memberNoticeEvent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public Map<String, Object> getDriverBusy(Long employId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean busy = true;
        String message = "";
        Integer code = 0;
        if (employId != null) {
            try {
                ServiceSetting serviceSetting = ServiceUtil.checkOpen();

                if (serviceSetting.isDaijia()) {
                    Long daijiaAmount = orderService.countActivedOrdersByDriver(employId);
                    if (daijiaAmount > 0) {
                        System.err.println(employId + "还有未完成的代驾工单,不能派单");
                        busy = false;
                        message = "还有未完成的代驾工单,不能派单";
                        code = -1;
                    }
                }

                if (serviceSetting.isZhuanche()) {
                    Long zhuancheAmount = zhuancheService.countActivedOrdersByDriver(employId);
                    if (zhuancheAmount > 0) {
                        System.err.println(employId + "还有未完成的专车工单,不能派单");
                        busy = false;
                        message = "还有未完成的专车工单,不能派单";
                        code = -2;
                    }
                }

                if (serviceSetting.isPaotui()) {
                    Long paotuiAmount = errandService.countBusyAmount(employId);
                    if (paotuiAmount > 0) {
                        System.err.println(employId + "还有未完成的跑腿工单,不能派单");
                        busy = false;
                        message = "还有未完成的跑腿工单,不能派单";
                        code = -3;
                    }
                }

                if (serviceSetting.isFreight()) {
                    Long huoyunAmount = freightService.countActivedOrdersByDriver(employId);
                    if (huoyunAmount > 0) {
                        System.err.println(employId + "还有未完成的货运工单,不能派单");
                        busy = false;
                        message = "还有未完成的货运工单,不能派单";
                        code = -4;
                    }
                }

                if (serviceSetting.isZhuanxian()) {
                    Long zhuanxianAmount = zhuanxianService.countActivedOrdersByDriver(employId);
                    if (zhuanxianAmount > 0) {
                        System.err.println(employId + "还有未完成的专线工单,不能派单");
                        busy = false;
                        message = "还有未完成的专线工单,不能派单";
                        code = -5;
                    }
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            busy = false;
        }
        map.put("success", busy);
        map.put("message", message);
        map.put("code", code);
        return map;
    }

}
